import java.util.concurrent.Semaphore;
import java.util.Random;

public class Read extends Thread {
    private int num;

    public Read(int num) {
        this.num = num;
        this.setName("读者" + num);
    }

    @Override
    public void run() {
        try {
            Random random = new Random();
            Thread.sleep(random.nextInt(500)); // 模拟准备读

            ReadAndWrite.insert1(getName() + " 打算读文件");
            ReadAndWrite.Re.add(getName() + " 打算读文件");

            ReadAndWrite.w.acquire();
            ReadAndWrite.mutex.acquire();
            if (ReadAndWrite.count == 0)
                ReadAndWrite.rw.acquire(); // 第一个读者阻止写者
            ReadAndWrite.count++;
            ReadAndWrite.mutex.release();
            ReadAndWrite.w.release();

            // 正在读文件
            ReadAndWrite.insert2(getName() + " 正在读文件");
            ReadAndWrite.ing.add(getName() + " 正在读文件");
            Thread.sleep(random.nextInt(5000) + 1500);
            ReadAndWrite.insert2(getName() + " 结束读文件");
            ReadAndWrite.insert1(getName() + " 完成读文件");
            ReadAndWrite.ing.remove(getName() + " 正在读文件");
            ReadAndWrite.Re.remove(getName() + " 打算读文件");

            Thread.sleep(3000); // 模拟处理完毕后刷新
            ReadAndWrite.fresh.acquire();
            ReadAndWrite.refresh();
            ReadAndWrite.fresh.release();

            ReadAndWrite.mutex.acquire();
            ReadAndWrite.count--;
            if (ReadAndWrite.count == 0)
                ReadAndWrite.rw.release(); // 最后一个读者释放写者
            ReadAndWrite.mutex.release();

        } catch (InterruptedException e) {
            System.out.println(getName() + " 出现错误！");
            e.printStackTrace();
        }
    }
}
